<template>
  <div class="app-container">
    <el-form ref="postForm" :model="form" :rules="formRules" label-width="120px">
      <el-form-item label="标题" required prop="title">
        <el-input v-model="form.title" placeholder="please input title"/>
      </el-form-item>
      <el-form-item label="作者" required prop="user_id">
        <el-select v-model="form.user_id" placeholder="please select author">
          <el-option v-for="user in userList" :key="user.id" :label="user.name" :value="user.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" required prop="content">
        <div>
          <tinymce v-model="form.content" :height="300"/>
        </div>
        <div class="editor-content" v-html="form.content"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">添加</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { getList } from '@/api/user'
import { create as createPost, show as getDetail, update as updatePost } from '@/api/post'

export default {
  name: 'PostsCreate',
  components: { Tinymce },
  data() {
    return {
      form: {
        title: '',
        content: '',
        user_id: undefined
      },
      formRules: {
        title: [
          { required: true, message: 'please input title', trigger: 'blur' }
        ],
        content: [
          { required: true, message: 'please input content', trigger: 'blur' }
        ],
        user_id: [
          { required: true, message: 'please select author', trigger: 'blur' }
        ]
      },
      userList: []
    }
  },
  created() {
    this.getUserList()
    this.getDetail()
  },
  methods: {
    async getUserList() {
      const {data} = await getList()
      this.userList = data.items || []
    },
    async onSubmit() {
      this.$refs.postForm.validate(async valid => {
        if (valid) {
          const res = this.form.id ? await updatePost(this.form.id, this.form) : await createPost(this.form)
          if (res.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$refs.postForm.resetFields()
            this.form.id ? await this.getDetail() : await this.$router.push({name: 'List'})
          }
        }
      })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    async getDetail() {
      let detailData = this.$route.query.id ? await getDetail(this.$route.query.id) : {}
      this.form = this.$route.query.id ? detailData.data : this.form
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>

